#!/bin/bash

ULOZENKAPRICE=36
PARTNERPRICE=55

#wget https://api.ulozenka.cz/v2//branches?shopid=1 -O list.json


for i in $(seq 0 199); do

  JSON.sh -b <list.json | grep -F "[\"data\",$i," >$(printf %03d $i).info

done

find . -size 0 -iname "*.info" -delete

for i in *.info; do
  echo $i
  grep -e "\[.*\,\"active\".*\].*0$" $i && rm $i
  grep -e "\[.*\,\"partner\".*\].*0$" $i && mv $i ulozenka
  grep -e "\[.*\,\"partner\".*\].*1$" $i && mv $i partners
done

## extract shortcut - name

rm ulozenka.list
for i in ulozenka/*.info; do
  SHORTCUT=$(grep -e "\[.*\,\"shortcut\".*\].*" $i | cut -f2 -d"]")
  NAME=$(grep -e "\[.*\,\"name\".*\].*" $i | head -n1 | cut -f2 -d"]")
  echo $SHORTCUT - $NAME | native2ascii -encoding UTF-8 -reverse | sed -e 's/\\\//\//g' | sed -e 's/\"//g' >> ulozenka.list
done

rm partners.list
for i in partners/*.info; do
  SHORTCUT=$(grep -e "\[.*\,\"shortcut\".*\].*" $i | cut -f2 -d"]")
  NAME=$(grep -e "\[.*\,\"name\".*\].*" $i | head -n1 | cut -f2 -d"]")
  echo $SHORTCUT - $NAME | native2ascii -encoding UTF-8 -reverse | sed 's/\\\//\//g' | sed -e 's/\"//g' >> partners.list
done

TABLE=zen_configuration
SQLCOMMAND1="INSERT INTO"
SQLCOMMAND2="(configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) VALUES "

DATETIME=$(date "+%Y-%m-%d %T")


echo "DELETE FROM \`$TABLE\` WHERE configuration_key LIKE 'MODULE_SHIPPING_ULOZENKA_OPT_%' OR configuration_key LIKE 'MODULE_SHIPPING_ULOZENKA_COST_%';" > mylist.sql

for i in $(seq 1 $(wc -l ulozenka.list  | cut -f1 -d" ")) ; do
  INDEX=$(( i - 1 ))
  NAME=$(sed -n ${i}p ulozenka.list)
  echo "$SQLCOMMAND1 \`$TABLE\` $SQLCOMMAND2 ('Option $INDEX Description', 'MODULE_SHIPPING_ULOZENKA_OPT_$INDEX', '$NAME', 'Description of option $INDEX', '6', '0', 'zen_cfg_textarea(', '$DATETIME');" >> mylist.sql
  echo "$SQLCOMMAND1 \`$TABLE\` $SQLCOMMAND2 ('Option $INDEX Description', 'MODULE_SHIPPING_ULOZENKA_COST_$INDEX', '$ULOZENKAPRICE', 'Shipping rate for option $INDEX', '6', '0', NULL, '$DATETIME');" >> mylist.sql
done


echo "DELETE FROM \`$TABLE\` WHERE configuration_key LIKE 'MODULE_SHIPPING_UPARTNER_OPT_%' OR configuration_key LIKE 'MODULE_SHIPPING_UPARTNER_COST_%';" >> mylist.sql

for i in $(seq 1 $(wc -l partners.list  | cut -f1 -d" ")) ; do
  INDEX=$(( i - 1 ))
  NAME=$(sed -n ${i}p partners.list)
  echo "$SQLCOMMAND1 \`$TABLE\` $SQLCOMMAND2 ('Option $INDEX Description', 'MODULE_SHIPPING_UPARTNER_OPT_$INDEX', '$NAME', 'Description of option $INDEX', '6', '0', 'zen_cfg_textarea(', '$DATETIME');" >> mylist.sql
  echo "$SQLCOMMAND1 \`$TABLE\` $SQLCOMMAND2 ('Option $INDEX Description', 'MODULE_SHIPPING_UPARTNER_COST_$INDEX', '$PARTNERPRICE', 'Shipping rate for option $INDEX', '6', '0', NULL, '$DATETIME');" >> mylist.sql
done




